<template>
  <Split
    direction="horizontal"
    :style="{ height: '100%' }"
    v-model:size="splitSize"
    :resize-trigger-size="5"
    :min="0"
    :max="0.23"
  >
    <template #1>
      <OrgTree
        ref="orgTreeRef"
        @hide="handleHideOrgTree"
        @set="handleSetOrg"
        @reload="reloadData"
        @loaded="handleOrgTreeLoaded"
      />
    </template>

    <template #2>
      <n-card
        :segmented="{ content: true }"
        :bordered="false"
        size="small"
        :style="{ height: '100%', 'padding-top': '8px' }"
      >
        <template #header>
          <n-space>
            <n-button
              type="primary"
              @click="handleAddFence"
              v-permission="{ action: ['fenceManager_setting_add'] }"
            >
              <template #icon>
                <n-icon><PlusOutlined /></n-icon>
              </template>
              设置电子围栏
            </n-button>

            <n-button
              v-if="isDrawing"
              type="success"
              @click="handleSaveFence"
              v-throttle="saveFence"
            >
              <template #icon>
                <n-icon><CheckOutlined /></n-icon>
              </template>
              保存围栏
            </n-button>

            <n-button v-if="isDrawing" type="warning" @click="handleCancelDraw">
              <template #icon>
                <n-icon><CloseOutlined /></n-icon>
              </template>
              取消
            </n-button>

            <n-button
              type="error"
              @click="handleClearFence"
              v-permission="{ action: ['fenceManager_setting_delete'] }"
            >
              <template #icon>
                <n-icon><DeleteOutlined /></n-icon>
              </template>
              清除围栏
            </n-button>

            <n-button v-if="isDrawing" @click="handleResetFence">
              <template #icon>
                <n-icon><ReloadOutlined /></n-icon>
              </template>
              重置
            </n-button>
          </n-space>
        </template>

        <n-alert type="info" :show-icon="false" style="margin-bottom: 10px">
          <b>配置操作说明:</b>
          <p
            >1、点击设置按钮，进入电子围栏绘制状态。<br />
            2、鼠标左键点击地图，可开始绘制电子围栏。<br />
            3、连续左键点击形成电子围栏区域，点击鼠标右键，完成绘制。<br />
            4、点击保存按钮，完成电子围栏配置操作。</p
          >
        </n-alert>

        <OfflineMap
          ref="mapRef"
          :org-id="selectedOrgId"
          :is-draw="isDrawing"
          :draw-option="{ fence: true, track: true }"
          :height="63"
        />
      </n-card>
    </template>

    <template #resize-trigger>
      <div class="spliter" title="双击隐藏组织机构" @dblclick.prevent="toggleOrgTree"></div>
    </template>
  </Split>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick, reactive } from 'vue';
  import { useMessage } from 'naive-ui';
  import { Split } from '@/components/Split';
  import OrgTree from '@/views/businessPages/comp/org/orgTree.vue';
  import OfflineMap from '@/views/businessPages/comp/map/offlineMap.vue';
  import {
    PlusOutlined,
    CheckOutlined,
    CloseOutlined,
    DeleteOutlined,
    ReloadOutlined,
  } from '@vicons/antd';
  import gcoord from 'gcoord';

  // API 导入（需要根据实际路径调整）
  import { saveFenceConfig, clearFenceConfig, getFenceConfig } from '@/api/business/fenceManager/fence';

  const message = useMessage();

  // 响应式数据
  const splitSize = ref(0.23);
  const selectedOrgId = ref('');
  const isDrawing = ref(false);
  const mapRef = ref();
  const orgTreeRef = ref();

  // 添加一个 ref 来标识组织树是否已加载
  const orgTreeLoaded = ref(false);

  // 初始化数据
  async function initializeMapWithRootNode() {
    if (orgTreeRef.value && typeof orgTreeRef.value.getRootNodeId === 'function') {
      const rootId = orgTreeRef.value.getRootNodeId();
      if (rootId) {
        selectedOrgId.value = rootId;
        reloadData();
      }
    }
  }

  // 处理隐藏组织树
  function handleHideOrgTree() {
    splitSize.value = 0;
  }

  // 切换组织树显示
  function toggleOrgTree() {
    splitSize.value = splitSize.value > 0 ? 0 : 0.23;
  }

  // 设置选中组织
  function handleSetOrg(orgId: string) {
    selectedOrgId.value = orgId;
    // 触发加载逻辑
  }

  // 重新加载数据
  async function reloadData() {
    if (mapRef.value) {
      await mapRef.value.loadStationData(selectedOrgId.value);
    }
  }

  // 处理组织机构树加载完成事件
  function handleOrgTreeLoaded() {
    // 获取组织树的根节点数量
    const orgTreeComponent = orgTreeRef.value;
    if (orgTreeComponent) {
      // 获取所有节点
      const allNodes = orgTreeComponent.toArray();

      // 如果节点数量小于等于1，默认隐藏树结构
      if (allNodes && allNodes.length <= 1) {
        splitSize.value = 0;
      } else {
        // 否则保持默认大小
        splitSize.value = 0.23;
      }
    }
    // 获取根节点并初始化表格
    initializeMapWithRootNode();
  }

  // 处理添加围栏
  function handleAddFence() {
    isDrawing.value = true;
    if (mapRef.value) {
      mapRef.value.drawFence();
    }
  }

  // 保存围栏
  async function saveFence() {
    if (!mapRef.value) return;

    const fence = mapRef.value.getFence();
    if (!fence) {
      // 清除围栏配置
      await clearFenceConfig({ orgId: selectedOrgId.value });
      return;
    }

    const path = fence.getPath();
    if (path.length < 3) {
      message.warning('围栏至少需要3个点');
      return;
    }

    // 转换坐标
    const coordinatesList = path.map((point: any, index: number) => {
      const transformed = gcoord.transform([point.lng, point.lat], gcoord.GCJ02, gcoord.WGS84);
      return {
        longitude: transformed[0],
        latitude: transformed[1],
        sort: index,
      };
    });

    try {
      const params = {
        orgId: selectedOrgId.value,
        coordinatesList,
      };
      await saveFenceConfig(params);
      message.success('围栏保存成功');
      isDrawing.value = false;
    } catch (error) {
      message.error('保存失败: ' + (error.message || '未知错误'));
    }
  }

  // 处理保存围栏（包装方法）
  function handleSaveFence() {
    saveFence();
  }

  // 取消绘制
  function handleCancelDraw() {
    isDrawing.value = false;
    if (mapRef.value) {
      mapRef.value.clearFence();
    }
  }

  // 清除围栏
  async function handleClearFence() {
    if (!selectedOrgId.value) {
      message.warning('请先选择组织机构');
      return;
    }

    try {
      await clearFenceConfig({ orgId: selectedOrgId.value });
      if (mapRef.value) {
        mapRef.value.clearFence();
      }
      message.success('围栏清除成功');
    } catch (error) {
      message.error('清除失败: ' + (error.message || '未知错误'));
    }
  }

  // 重置围栏
  function handleResetFence() {
    if (mapRef.value) {
      mapRef.value.clearFence();
      mapRef.value.loadFence();
    }
  }
</script>

<style scoped>
  .spliter {
    cursor: col-resize;
    background-color: #e5e7eb;
    height: 100%;
    width: 5px;
  }

  .spliter:hover {
    background-color: #9ca3af;
  }
</style>
